'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')

function resolve(dir) {
    return path.join(__dirname, dir)
}

const name = defaultSettings.title || 'vue Admin Template' // page title

const port = process.env.port || process.env.npm_config_port || 9528 // dev port

// 通过环境变量 来区分是否使用cdn
let cdn = { css: [], js: [] }
const isProd = process.env.NODE_ENV === 'production' // 判断是否是生产环境
let externals = {}
    // 引入CDN配置文件
    // 这时的配置实际上是对开发环境和生产环境都生效的，在开发环境时，没有必要使用CDN，此时我们可以使用环境变量来进行区分

if (isProd) {
    // 只有当生产环境下， 才有必要去做排除和CDN打包
    externals = {
        'vue': 'Vue',
        'element-ui': 'ELEMENT',
        'xlsx': 'XLSX'
    }
    cdn = {
        css: [
            'https://unpkg.com/element-ui/lib/theme-chalk/index.css' // 提前引入elementUI样式
        ], // 放置css文件目录
        js: [
                'https://cdn.jsdelivr.net/npm/vue@2.6.14', // vuejs
                'https://unpkg.com/element-ui/lib/index.js', // element
                'https://cdn.jsdelivr.net/npm/xlsx@0.16.6/dist/xlsx.full.min.js', // xlsx 相关
                'https://cdn.jsdelivr.net/npm/xlsx@0.16.6/dist/jszip.min.js' // xlsx 相关
            ] // 放置js文件目录
    }

}

module.exports = {

    publicPath: '/',
    outputDir: 'dist',
    assetsDir: 'static',
    lintOnSave: process.env.NODE_ENV === 'development',
    productionSourceMap: false,
    devServer: {
        port: port,
        open: true,
        overlay: {
            warnings: false,
            errors: true
        },
        // 在devServer中，配置反向代理
        proxy: {
            // 当地址中有/api的时候，会触发反向代理机制
            '/api': {
                target: 'http://ihrm.itheima.net/', // 要代理的服务器地址，这里不用谢api
                changeOrigin: true // 是否跨域
            }
        }
    },
    // 配置webpack属性
    configureWebpack: {
        name: name,
        resolve: {
            alias: {
                '@': resolve('src')
            }
        },
        // 排除打包，放到CDN服务器上
        // externals：外部的
        // key:表示要排除的包名
        // value:实际上是实际引入的包的 全局的变量名
        // 因为要排除vue等三个文件，所以后面要引入CDN文件，CDN文件中有Vue的全局变量名
        externals: externals
    },

    chainWebpack(config) {
        // it can improve the speed of the first screen, it is recommended to turn on preload
        config.plugin('preload').tap(() => [{
            rel: 'preload',
            // to ignore runtime.js
            // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
            fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
            include: 'initial'
        }])

        // 在webpack执行链中， 注入CDN
        // 这样代码，会在执行webpack打包的时候执行。执行的时候会将CDN变量注入到html模板中
        config.plugin('html').tap(args => {
            args[0].cdn = cdn
            return args
        })

        // when there are many pages, it will cause too many meaningless requests
        config.plugins.delete('prefetch')

        // set svg-sprite-loader
        config.module
            .rule('svg')
            .exclude.add(resolve('src/icons'))
            .end()
        config.module
            .rule('icons')
            .test(/\.svg$/)
            .include.add(resolve('src/icons'))
            .end()
            .use('svg-sprite-loader')
            .loader('svg-sprite-loader')
            .options({
                symbolId: 'icon-[name]'
            })
            .end()

        config
            .when(process.env.NODE_ENV !== 'development',
                config => {
                    config
                        .plugin('ScriptExtHtmlWebpackPlugin')
                        .after('html')
                        .use('script-ext-html-webpack-plugin', [{
                            // `runtime` must same as runtimeChunk name. default is `runtime`
                            inline: /runtime\..*\.js$/
                        }])
                        .end()
                    config
                        .optimization.splitChunks({
                            chunks: 'all',
                            cacheGroups: {
                                libs: {
                                    name: 'chunk-libs',
                                    test: /[\\/]node_modules[\\/]/,
                                    priority: 10,
                                    chunks: 'initial' // only package third parties that are initially dependent
                                },
                                elementUI: {
                                    name: 'chunk-elementUI', // split elementUI into a single package
                                    priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                                    test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                                },
                                commons: {
                                    name: 'chunk-commons',
                                    test: resolve('src/components'), // can customize your rules
                                    minChunks: 3, //  minimum common number
                                    priority: 5,
                                    reuseExistingChunk: true
                                }
                            }
                        })
                        // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
                    config.optimization.runtimeChunk('single')
                }
            )
    }
}